package model.fshare.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;

public class FileSender implements Runnable
{
	private Socket dataDestination;
	private String fileName;
	private int roomId;
	
	public FileSender(Socket socket, int roomId, String fileName)
	{
		dataDestination = socket;
		this.fileName = fileName;
		this.roomId = roomId;
	}
	
	@Override
	public void run()
	{
		File fileToSend = new File( "SharedFiles/" + roomId + "/" + fileName );
		try 
		{
			DataInputStream fileReader = new DataInputStream( new BufferedInputStream( new FileInputStream( fileToSend ) ) );

			DataOutputStream dataWriter = new DataOutputStream( new BufferedOutputStream( dataDestination.getOutputStream() ) );
			
			byte[] buf = new byte[1024*10];
			int bytesReaded = 0;
			try
			{
				while( (bytesReaded = fileReader.read(buf)) != -1 )
				{
					dataWriter.write( buf, 0, bytesReaded );
					dataWriter.flush();
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
			fileReader.close();
			dataDestination.close();
		}
		catch ( Exception e ) 
		{
			e.printStackTrace();
		}
	}

}
